﻿using AutoMapper;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;
using Volo.Abp;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Volo.Abp.Domain.Repositories;
using WMSSystem.DYB;
using WMSSystem.DYB.Dto.Department;
using WMSSystem.WYJ.Dto;
using WMSSystem.WYJ.Interfance;
using WMSSystem.YJ;
using WMSSystem.YJ.DTO.Out;

namespace WMSSystem.WYJ
{
    public class SalesReturnServices : ApplicationService, ISalesReturnServices
    {
        IRepository<WYJ_SalesReturn, Guid> _salesReturnRepository;
        IRepository<WYJ_SalesOrder, Guid> _salesOrderRepository;
        IRepository<Statuswyj, Guid> _statuswyjRepository;
        IRepository<Commoditiestable, Guid> _commoditiesRepository;
        IRepository<WYJ_GoodsforSale, Guid> _goodsforSaleRepository;
        IRepository<WYJ_SalesNumber, Guid> _salesNumberRepository;
        IMapper _mapper;

        public SalesReturnServices(IRepository<WYJ_SalesReturn, Guid> salesReturnRepository, IRepository<WYJ_SalesOrder, Guid> salesOrderRepository, IRepository<Statuswyj, Guid> statuswyjRepository, IRepository<Commoditiestable, Guid> commoditiesRepository, IRepository<WYJ_GoodsforSale, Guid> goodsforSaleRepository, IRepository<WYJ_SalesNumber, Guid> salesNumberRepository, IMapper mapper)
        {
            _salesReturnRepository = salesReturnRepository;
            _salesOrderRepository = salesOrderRepository;
            _statuswyjRepository = statuswyjRepository;
            _commoditiesRepository = commoditiesRepository;
            _goodsforSaleRepository = goodsforSaleRepository;
            _salesNumberRepository = salesNumberRepository;
            _mapper = mapper;
        }

        /// <summary>
        /// 创建销售退货
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CreateSalesReturnDto> CreateSalesReturnAsync(CreateSalesReturnDto input)
        {
            var salesReturn = _mapper.Map<CreateSalesReturnDto,WYJ_SalesReturn>(input);
            await _salesReturnRepository.InsertAsync(salesReturn);
            return _mapper.Map<WYJ_SalesReturn, CreateSalesReturnDto>(salesReturn); ;
        }
        /// <summary>
        /// 获取销售退货列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetSalesReturnList>> GetSalesReturnListAsync()
        {
            var salesReturn = await _salesReturnRepository.GetListAsync();
            var salesOrder = await _salesOrderRepository.GetListAsync();
            var salesreturn= await _salesNumberRepository.GetListAsync();
            var statuswyj = await _statuswyjRepository.GetListAsync();
            var commodities = await _commoditiesRepository.GetListAsync();

            var query = from a in salesReturn
                        join b in salesOrder on a.OrderCode equals b.OrderCodes
                        join c in statuswyj on a.StatusCode equals c.StatusCode
                        join d in commodities on a.CommodityCode equals d.CommoditiesCode
                        select new GetSalesReturnList
                        {
                            StatusCode = c.StatusCode,
                            CommodityCode = a.CommodityCode,
                            ReturnCodes = a.ReturnCodes,
                            ReturnDates = a.ReturnDates,
                            OrderCodes = b.OrderCodes,
                            CustomerNames = b.CustomerName,
                            People = b.People,
                            Phone = b.Phone,
                            SalesDept = b.SalesDept,
                            SalesPerson = b.SalesPerson,
                            CommoditiesName = d.CommoditiesName,
                            Stautsname = c.Stautsname,
                            Manager = c.Manager
                            
                        };
            return query.ToList();
        }


        /// <summary>
        /// 货品明细
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CreateReturnDetails> CreateReturnDetailsAsync(CreateReturnDetails input)
        {
            try
            {
                // 1. 映射实体
                var returnDetails = _mapper.Map<CreateReturnDetails, WYJ_SalesNumber>(input);

                // 2. 设置ID和创建时间
              
                returnDetails.CreationTime = DateTime.Now;

                // 3. 只插入一次！
                var insertedDetails = await _salesNumberRepository.InsertAsync(returnDetails);

                // 4. 立即保存
                await CurrentUnitOfWork.SaveChangesAsync();

                // 5. 返回结果
                return _mapper.Map<WYJ_SalesNumber, CreateReturnDetails>(insertedDetails);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "创建货品明细失败");
                throw new UserFriendlyException("创建货品明细失败: " + ex.Message);
            }
        }
        /// 货品明细列表
        public async Task<List<GetReturnDetailsList>> GetReturnDetailsListAsync()
        {
           var goods=await _goodsforSaleRepository.GetListAsync();
            var salesreturn= await _salesNumberRepository.GetListAsync();
            var query = from a in goods
                        join b in salesreturn on a.CommoditiesCode equals b.NumberCodes
                        select new GetReturnDetailsList
                        {
                            CommoditiesName = a.CommoditiesName,
                            CommoditiesCode = a.CommoditiesCode,
                            CommoditiesGuike = a.CommoditiesGuike,
                            UnitName = a.UnitName,
                            SalesNums = a.SalesNums,
                            Output = a.Output,
                            Input = a.Input,
                            UnitPrice = a.UnitPrice,
                            SalesAmount = a.SalesAmount,
                            PresetTwo=a.PresetTwo,
                            NumberCodes = b.NumberCodes,
                            ReturnNum = b.ReturnNum,
                            NumberMoney = b.NumberMoney,
                            NumMsg = b.NumMsg
                        };
            return  query.ToList();

        }



        // <summary>
        /// 销售退货删除 - 通过退货单号
        /// </summary>
        /// <param name="returnCode">退货单号</param>
        /// <returns></returns>
        public async Task SRDeleteByCodeAsync(string returnCode)
        {
            // 1. 根据退货单号查找退货单
            var salesReturn = await _salesReturnRepository.FirstOrDefaultAsync(x => x.ReturnCodes == returnCode);
            if (salesReturn == null)
            {
                throw new UserFriendlyException("退货单不存在");
            }

            // 2. 业务验证
            if (salesReturn.StatusCode == "已完成")
            {
                throw new UserFriendlyException("已完成的退货单不能删除");
            }

            
            // 4. 删除主记录
            await _salesReturnRepository.DeleteAsync(salesReturn.Id);
        }

        public async Task<List<GetStatuslist>> GetStatusListAsync()
        {
            var status = await _statuswyjRepository.GetListAsync();
            var result = status.Select(o => new GetStatuslist
            {
               
                StatusCode = o.StatusCode,
                Stautsname = o.Stautsname,
                Manager = o.Manager


                // 如有其他字段请补充
            }).ToList();

            return result;
        }
        /// <summary>
        /// 创建销售订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        public async Task<CreateOrder> CreateOrderAsync(CreateOrder input)
        {

            try
            {
                // 1. 检查订单号是否已存在（防止重复）
                var existingOrder = await _salesOrderRepository.FirstOrDefaultAsync(x => x.OrderCodes == input.OrderCodes);
                if (existingOrder != null)
                {
                    throw new UserFriendlyException($"订单号 {input.OrderCodes} 已存在，请重新生成订单号");
                }

                // 2. 映射并创建订单实体
                var salesOrder = _mapper.Map<CreateOrder, WYJ_SalesOrder>(input);

               
                salesOrder.CreationTime = DateTime.Now;

                // 4. 只插入一次！
                var insertedOrder = await _salesOrderRepository.InsertAsync(salesOrder);

                // 5. 立即保存到数据库
                await CurrentUnitOfWork.SaveChangesAsync();

                // 6. 返回插入后的数据
                return _mapper.Map<WYJ_SalesOrder, CreateOrder>(insertedOrder);
            }
            catch (Exception ex)
            {
                Logger.LogError(ex, "创建销售订单失败，订单号: {OrderCodes}", input.OrderCodes);
                throw new UserFriendlyException("创建销售订单失败: " + ex.Message);
            }
        }
        /// <summary>
        /// 销售订单列表
        /// </summary>
        /// <returns></returns>
        public async Task<List<GetSalesOrderList>> GetSalesOrderListAsync()
        {
            var orders = await _salesOrderRepository.GetListAsync();
            var huopin=await _goodsforSaleRepository.GetListAsync();
            var statuswyj = await _statuswyjRepository.GetListAsync();
           var query=from a in orders
                     join b in huopin on a.PresetThree equals b.PresetThree
                     join c in statuswyj on a.OrderStatus equals c.StatusCode
                     select new GetSalesOrderList
                     {
                         OrderCodes = a.OrderCodes,
                         CustomerName = a.CustomerName,
                         People = a.People,
                         Phone = a.Phone,
                         SalesDept = a.SalesDept,
                         SalesPerson = a.SalesPerson,
                         SalesNums = b.SalesNums,
                         SalesAmount = b.SalesAmount,
                         OrderStatus = c.Stautsname,
                         Manager = c.Manager,
                         PresetOne=a.PresetOne,
                         PresetThree=a.PresetThree,
                         CommoditiesName=b.CommoditiesName
                     };
            return query.ToList();
        }
        /// <summary>
        /// 审核销售退货
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<string> AuditSalesReturnAsync(AuditSalesReturnDto input)
        {
            try
            {
                var salesReturn = await _salesReturnRepository.FirstOrDefaultAsync(x => x.ReturnCodes == input.ReturnCode);
                if (salesReturn == null)
                {
                    throw new UserFriendlyException("订单不存在");
                }

                // 直接使用状态表中的编号
                if (input.AuditResult == "通过")
                {
                    salesReturn.StatusCode = "2"; // 替换为你状态表中"已完成"的实际编号
                }
                else if (input.AuditResult == "驳回")
                {
                    salesReturn.StatusCode = "3"; // 替换为你状态表中"驳回"的实际编号
                }

                await _salesReturnRepository.UpdateAsync(salesReturn);

                return "审核完成";
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"审核失败：{ex.Message}");
            }
        }
        /// <summary>
        /// 删除销售订单
        /// </summary>
        /// <param name="orderCode"></param>
        /// <returns></returns>
        /// <exception cref="NotImplementedException"></exception>
        public async Task SRDeleteOrderAsync(string orderCode)
        {
            // 1. 根据退货单号查找退货单
            var salesReturn = await _salesOrderRepository.FirstOrDefaultAsync(x => x.OrderCodes == orderCode);
            if (salesReturn == null)
            {
                throw new UserFriendlyException("退货单不存在");
            }

            // 2. 业务验证
            if (salesReturn.OrderStatus== "已完成")
            {
                throw new UserFriendlyException("已完成的订单不能删除");
            }


            // 4. 删除主记录
            await _salesOrderRepository.DeleteAsync(salesReturn.Id);
        }
        /// <summary>
        /// 审核销售订单
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        /// <exception cref="UserFriendlyException"></exception>
        public async Task<string> AuditOrderAsync(AuditSalesReturnDto input)
        {
            try
            {
                var salesReturn = await _salesOrderRepository.FirstOrDefaultAsync(x => x.OrderCodes == input.ReturnCode);
                if (salesReturn == null)
                {
                    throw new UserFriendlyException("退货单不存在");
                }

                // 直接使用状态表中的编号
                if (input.AuditResult == "通过")
                {
                    salesReturn.OrderStatus = "2"; // 替换为你状态表中"已完成"的实际编号
                }
                else if (input.AuditResult == "驳回")
                {
                    salesReturn.OrderStatus = "3"; // 替换为你状态表中"驳回"的实际编号
                }

                await _salesOrderRepository.UpdateAsync(salesReturn);

                return "审核完成";
            }
            catch (Exception ex)
            {
                throw new UserFriendlyException($"审核失败：{ex.Message}");
            }
        }

        //public async Task<PagedResultDto<GetSalesReturnOutput>> GetSalesReturnListAsync(GetSalesReturnList input)
        //{
        //    var salesReturn = await _salesReturnRepository.GetListAsync();
        //    var salesOrder = await _salesOrderRepository.GetListAsync();
        //    var statuswyj = await _statuswyjRepository.GetListAsync();
        //    var commodities = await _commoditiesRepository.GetListAsync();

        //    var query = from a in salesReturn
        //                join b in salesOrder on a.OrderCode equals b.OrderCodes
        //                join c in statuswyj on a.StatusCode equals c.StatusCode
        //                join d in commodities on a.CommodityCode equals d.CommoditiesCode
        //                select new GetSalesReturnOutput
        //                {
        //                    ReturnCodes = a.ReturnCodes,
        //                    ReturnDates = a.ReturnDates,
        //                    OrderCodes = b.OrderCodes,
        //                    CustomerNames = b.CustomerName,
        //                    People = b.People,
        //                    Phone = b.Phone,
        //                    SalesDept = b.SalesDept,
        //                    SalesPerson = b.SalesPerson,
        //                    OrderNum = b.OrderNum,
        //                    OrderMoney = b.OrderMoney,
        //                    CommoditiesName = d.CommoditiesName,
        //                    Stautsname = c.Stautsname,
        //                    Manager = c.Manager
        //                };
        //    var items = query.Skip(input.SkipCount).Take(input.MaxResultCount).ToList();

        //    return new PagedResultDto<GetSalesReturnOutput>(
        //        totalCount,
        //        ObjectMapper.Map<List<GetSalesReturnList>, List<GetSalesReturnOutput>>(items));
        //}


    }
}
